package service

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"gitee.com/actor168/gitserver/pkg/config"
	processed "gitee.com/actor168/gitserver/pkg/process"
	"github.com/gogs/git-module"
	"github.com/unknwon/com"
)

// MergeStyle represents the approach to merge commits into base branch.
type MergeStyle string

const (
	MERGE_STYLE_REGULAR MergeStyle = "create_merge_commit"
	MERGE_STYLE_REBASE  MergeStyle = "rebase_before_merging"
)

type PullRequestStatus int

const (
	PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
	PULL_REQUEST_STATUS_CHECKING
	PULL_REQUEST_STATUS_MERGEABLE
)

func (g *gitRepository) merge(pr PullRequest, baseGitRepo *git.Repository, mergeStyle MergeStyle, commitDescription string) (string, error) {
	headRepoPath := filepath.Join(config.Conf.Dir, pr.HeadRepo) + ".git"
	var err error
	// Create temporary directory to store temporary copy of the base repository,
	// and clean it up when operation finished regardless of succeed or not.
	tmpBasePath := filepath.Join(config.Conf.LocalPath, "data", com.ToStr(time.Now().Nanosecond())+".git")
	if err := os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
		return "", err
	}
	defer func() {
		_ = os.RemoveAll(filepath.Dir(tmpBasePath))
	}()

	// Clone the base repository to the defined temporary directory,
	// and checks out to base branch directly.
	var stderr string
	if _, stderr, err = processed.ExecTimeout(5*time.Minute,
		fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
		"git", "clone", "-b", pr.BaseBranch, baseGitRepo.Path(), tmpBasePath); err != nil {
		return "", fmt.Errorf("git clone: %s", stderr)
	}
	headGitRepo, err := git.Open(headRepoPath)
	if err != nil {
		return "", err
	}
	// Add remote which points to the head repository.
	if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
		fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
		"git", "remote", "add", "head_repo", headRepoPath); err != nil {
		return "", fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
	}

	// Fetch information from head repository to the temporary copy.
	if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
		fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
		"git", "fetch", "head_repo"); err != nil {
		return "", fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
	}

	remoteHeadBranch := "head_repo/" + pr.HeadBranch

	// Check if merge style is allowed, reset to default style if not
	//if mergeStyle == MERGE_STYLE_REBASE && !f.BaseRepo.PullsAllowRebase {
	//	mergeStyle = MERGE_STYLE_REGULAR
	//}

	switch mergeStyle {
	case MERGE_STYLE_REGULAR: // Create merge commit

		// Merge changes from head branch.
		if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
			"git", "merge", "--no-ff", "--no-commit", remoteHeadBranch); err != nil {
			return "", fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
		}

		//new 13684856438 repo
		//fmt.Println("HeadBranch,HeadUserName,HeadRepo.Name", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name)
		// Create a merge commit for the base branch.
		if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
			"git", "commit", fmt.Sprintf("--author='%s <%s>'", pr.UserName, "1571334850@qq.com"),
			"-m", fmt.Sprintf("Merge branch '%s' of %s into %s", pr.HeadBranch, pr.HeadRepo, pr.BaseBranch),
			"-m", commitDescription); err != nil {
			return "", fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
		}

	case MERGE_STYLE_REBASE: // Rebase before merging

		// Rebase head branch based on base branch, this creates a non-branch commit state.
		if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
			"git", "rebase", "--quiet", pr.BaseBranch, remoteHeadBranch); err != nil {
			return "", fmt.Errorf("git rebase [%s on %s]: %s", remoteHeadBranch, pr.BaseBranch, stderr)
		}

		// Name non-branch commit state to a new temporary branch in order to save changes.
		tmpBranch := com.ToStr(time.Now().UnixNano(), 10)
		if _, stderr, err := processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
			"git", "checkout", "-b", tmpBranch); err != nil {
			return "", fmt.Errorf("git checkout '%s': %s", tmpBranch, stderr)
		}

		// Check out the base branch to be operated on.
		if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
			"git", "checkout", pr.BaseBranch); err != nil {
			return "", fmt.Errorf("git checkout '%s': %s", pr.BaseBranch, stderr)
		}

		// Merge changes from temporary branch to the base branch.
		if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
			fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
			"git", "merge", tmpBranch); err != nil {
			return "", fmt.Errorf("git merge [%s]: %v - %s", tmpBasePath, err, stderr)
		}

	default:
		return "", fmt.Errorf("unknown merge style: %s", mergeStyle)
	}

	// Push changes on base branch to upstream.
	if _, stderr, err = processed.ExecDir(-1, tmpBasePath,
		fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
		"git", "push", baseGitRepo.Path(), pr.BaseBranch); err != nil {
		return "", fmt.Errorf("git push: %s", stderr)
	}
	MergedCommitID, err := headGitRepo.BranchCommitID(pr.HeadBranch)

	return MergedCommitID, nil
}
